import {createSlice} from "@reduxjs/toolkit";
import {getFindByParentId} from "@/api/dict";
import {useSelector} from "react-redux";

const getInfoById = (arr:any[],id:number):any=>{
    let info;
    for(let i=0;i<arr.length;i++){
        if(arr[i].id === id){
            info=arr[i];
        }else if(arr[i].children && arr[i].children.length>0){
            info = getInfoById(arr[i].children,id);
        }
        if(info) break;
    }
    return info;
}


const dictSlice = createSlice({
    name:"dict",
    initialState:{
        dictList:[],// 保存获取过来的数据字典数据
        loading:false
    },
    reducers:{
        upLoading(state,{payload}){
            state.loading = payload;
        },
        upDictList(state,{payload}){
            // payload：{dictList,parentId}
            // const info:any = state.dictList.find((v:any)=>v.id === payload.parentId);
            // if(info){
            //     info.children = payload.dictList;
            // }else{
            //     state.dictList = payload.dictList;
            // }


            const info:any = getInfoById(state.dictList,payload.parentId);
            if(info) info.children = payload.dictList;
            else state.dictList = payload.dictList;
        }
    }
})
const {upDictList,upLoading} = dictSlice.actions;
// parentId 86
export const getFindByParentIdAsync = (parentId:number)=>{
    return async (dispatch:any)=>{
        dispatch(upLoading(true));
        const result = await getFindByParentId(parentId);
        dispatch(upDictList({
            dictList:result.data.map((item:any)=>{
                // 判断是否拥有子类型，如果有增加名字为children的属性，值为[]
                if(item.hasChildren){
                    item.children = []
                }
                return item;
            }),
            parentId
        }));
        dispatch(upLoading(false));
    }
}
export const useSelectorDict = ()=> useSelector((state:any)=>state.dict);
export default dictSlice.reducer;